let app = getApp();
let userLoginInfo = {};
const modules = 'cm_universal_form';

/**
 * 图片上传
 */
userLoginInfo.upload = function(option = {}) {
  let url = 'utility/file/upload';
  if (url.indexOf('http://') == -1 && url.indexOf('https://') == -1) {
    url = app.util.url(
      url,
      {
      type: 'image',
        thumb: '0',
      },
      modules,
    );
  }
  wx.chooseImage({
    count: option.count || 1, // 默认1
    sizeType: option.sizeType || ['compressed'], // 可以指定是原图还是压缩图，默认压缩图
    sourceType: option.sourceType || ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
    success: function(files) {
      //返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
      let responsePath = {};
      let tempFilePaths = files.tempFilePaths;
      responsePath.tempFilePaths = tempFilePaths;
      if (option.complete && typeof option.complete === 'function') {
        option.complete(responsePath);
      }
      for (let i = 0; i < tempFilePaths.length; i++) {
        const filePath = tempFilePaths[i];
        wx.uploadFile({
            url: url,
          filePath,
            name: 'file',
            success: function(result) {
            if (typeof JSON.parse(result.data) !== 'object') {
              if (option.fail && typeof option.fail === 'function') {
                  option.fail({
                    code: 1,
                  message: '返回数据格式有误',
                  });
                }
              } else {
              let data = JSON.parse(result.data);
                if (result.statusCode == 200 && !data.error) {
                let responseData = {}; // 图片信息
                  responseData = data;
                  responseData.key = i;
                if (option.success && typeof option.success === 'function') {
                    option.success(responseData);
                  }
                } else {
                if (option.fail && typeof option.fail === 'function') {
                    option.fail(data.error);
                  }
                }
              }
          },
        }).onProgressUpdate((res) => {
          let responseProgress = {};
            responseProgress = res;
            responseProgress.key = i;
          if (option.progress && typeof option.progress === 'function') {
              option.progress(responseProgress);
            }
          });
      }
    },
  });
};

module.exports = userLoginInfo;
